package transfer

import (
	"context"
	"encoding/json"
	"fmt"
	"private-domain-overseas-service/app/task/api/internal/logic/stream"
	"private-domain-overseas-service/app/task/api/internal/svc"
	"private-domain-overseas-service/pkg/constant"
)

type TransferThirdCustomer struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTransferThirdCustomer(ctx context.Context, svcCtx *svc.ServiceContext) *TransferThirdCustomer {
	return &TransferThirdCustomer{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TransferThirdCustomer) Consume(key, val string) error {
	fmt.Printf("==================收到消息==================:%s\n", val)

	// 接受消息体进行解析
	var jsonData map[string]interface{}
	if err := json.Unmarshal([]byte(val), &jsonData); err != nil {
		fmt.Printf("==================消息解析失败==================:%s\n", err)
		return nil
	}

	// 验证参数
	if _, ok := jsonData["event"].(string); !ok {
		fmt.Printf("==================Event消息类型错误==================:%s\n", val)
		return nil
	}
	if _, ok := jsonData["message"].(map[string]interface{}); !ok {
		fmt.Printf("==================Message消息类型错误==================:%s\n", val)
		return nil
	}

	// 根据消息事件处理逻辑进行消费
	var err error
	switch jsonData["event"] {
	case constant.StreamDyOrder:
		// 抖音订单回调
		third := stream.NewStreamDyOrder(l.ctx, l.svcCtx)
		err = third.DyOrderCallback(val)
		break
	default:
		fmt.Printf("==================找不到此消息==================:%s\n", val)
		return nil
	}

	// 记录消费失败 - 暂不处理
	if err != nil {
		return nil
	}
	return nil
}
